import { RouteRecordRaw } from "vue-router";

export function useRoutes(): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = [];
  const urls = import.meta.glob("@/pages/**/index.vue");

  for (const key in urls) {
    const urlStr = key;
    const path = urlStr.split("/").reverse();
    let index = path.length - 4;
    let children = routes;
    while (index > 0) {
      if (index === 1) {
        const route: RouteRecordRaw = {
          path: path.length === 5 ? `/${path[index]}` : path[index],
          name: path[index],
          component: () => import(key),
        };

        children.push(route);
      } else {
        let location = children.find(
          (child) => child.name === path[index]
        ) as RouteRecordRaw;
        if (!location.children) {
          (location as RouteRecordRaw).children = [];
        }
        children = location.children as RouteRecordRaw[];
      }

      index--;
    }
  }

  return routes;
}
